//
// Created by 李望轩 on 2020/11/20.
//
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "LeStruct.h"
#include "../LeCJson/cJSON.h"


int JsonWritFile(LeBookLink BookHead, LeStuLink StuHead) {
    cJSON *pRoot = NULL;//Json对象
    cJSON *pBookArray = NULL;//数组对象
    cJSON *pStuArray = NULL;//数组对象
    char *pJson = NULL;//字符串对象

    //创建数组对象
    pBookArray = cJSON_CreateArray();
    pStuArray = cJSON_CreateArray();

    //写入Book
    LeBookLink BookP = BookHead;
    while (BookP) {
        //创建Book节点对象
        pRoot = cJSON_CreateObject();
        cJSON_AddNumberToObject(pRoot, "BID", BookP->BID);
        cJSON_AddStringToObject(pRoot, "BName", BookP->BName);
        cJSON_AddStringToObject(pRoot, "BAName", BookP->BAName);
        cJSON_AddNumberToObject(pRoot, "BPID", BookP->BPID);
        cJSON_AddNumberToObject(pRoot, "BState", BookP->BState);
        cJSON_AddNumberToObject(pRoot, "SID", BookP->SID);
        BookP = BookP->Next;
        //添加到数组
        cJSON_AddItemToObject(pBookArray, "Book", pRoot);
        pRoot = NULL;
    }

    //写入Stu
    LeStuLink StuP = StuHead;
    while (StuP) {
        //创建Stu节点对象
        pRoot = cJSON_CreateObject();
        cJSON_AddNumberToObject(pRoot, "SID", StuP->SID);
        cJSON_AddStringToObject(pRoot, "SName", StuP->SName);
        cJSON_AddNumberToObject(pRoot, "SQuota", StuP->SQuota);
        cJSON_AddNumberToObject(pRoot, "SState", StuP->SState);
        StuP = StuP->Next;
        //添加到数组
        cJSON_AddItemToObject(pStuArray, "Stu", pRoot);
        pRoot = NULL;
    }

    pRoot = cJSON_CreateObject();//根节点并插入数组
    cJSON_AddItemToObject(pRoot, "Book", pBookArray);
    cJSON_AddItemToObject(pRoot, "Stu", pStuArray);

    pJson = cJSON_Print(pRoot);//解析成字符串
    //printf("%s\n", pJson);
    cJSON_Delete(pRoot);//释放json对象的空间
    pRoot = NULL;
    pBookArray = NULL;
    pStuArray = NULL;

    FILE *fp = NULL;
    fp = fopen("../Data/Data.json", "w+");
    fputs(pJson, fp);
    fclose(fp);
    free(pJson);//释放json的空间
    pJson = NULL;
    return 1;
}